<?php
namespace app\admin\controller;

use app\admin\model\Admin;
use think\facade\Session;

class Login extends \app\BaseController
{
    /**
     * 登录页面
     */
    public function index()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 如果已经登录，重定向到仪表板
        if (isset($_SESSION['admin_user'])) {
            return redirect('/admin/dashboard');
        }

        // 准备视图数据
        $data = [
            'title' => '管理员登录',
            'system_name' => '微信进件管理后台',
            'copyright' => '© 2025 微信进件管理系统',
            'captcha_url' => '/admin/captcha',
            'login_url' => '/admin/login',
            'dashboard_url' => '/admin/dashboard'
        ];

        // 使用视图渲染登录页面
        return view('login/index', $data);
    }
    
    /**
     * 执行登录
     */
    public function doLogin()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        
        // 验证参数
        if (empty($username) || empty($password)) {
            return json(['code' => 0, 'msg' => '用户名和密码不能为空']);
        }
        
        // 查找管理员
        $admin = Admin::where('username', $username)->find();
        if (!$admin) {
            return json(['code' => 0, 'msg' => '用户名不存在']);
        }
        
        // 检查状态
        if ($admin->status != 1) {
            return json(['code' => 0, 'msg' => '账号已被禁用']);
        }
        
        // 验证密码
        if (!password_verify($password, $admin->password)) {
            return json(['code' => 0, 'msg' => '密码错误']);
        }
        
        // 更新登录信息
        $admin->last_login_time = time();
        $admin->last_login_ip = $this->request->ip();
        $admin->save();
        
        // 设置session
        $adminData = [
            'id' => $admin->id,
            'username' => $admin->username,
            'nickname' => $admin->nickname,
            'email' => $admin->email,
            'role' => $admin->role ?: 'admin', // 默认为普通管理员
            'login_time' => time(),
            'last_activity' => time()
        ];
        
        $_SESSION['admin_user'] = $adminData;
        
        // 记录登录日志
        try {
            \think\facade\Db::name('admin_log')->insert([
                'admin_id' => $admin->id,
                'admin_name' => $admin->username,
                'action' => 'login',
                'description' => "管理员登录：{$admin->username}",
                'target_id' => $admin->id,
                'ip' => $this->request->ip(),
                'user_agent' => $this->request->header('User-Agent'),
                'create_time' => time()
            ]);
        } catch (\Exception $e) {
            // 日志记录失败不影响登录
        }
        
        // 调试信息
        logs('登录成功', [
            'session_id' => session_id(),
            'admin_data' => $adminData,
            'session_check' => isset($_SESSION['admin_user'])
        ]);
        
        return json(['code' => 1, 'msg' => '登录成功', 'url' => '/admin/dashboard']);
    }
    
    /**
     * 退出登录
     */
    public function logout()
    {
        if (!session_id()) {
            session_start();
        }
        unset($_SESSION['admin_user']);
        return redirect('/admin/login');
    }
    
    /**
     * 验证码生成
     */
    public function captcha()
    {
        // 关闭所有输出缓冲
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        try {
            // 创建图片
            $width = 120;
            $height = 40;
            $image = imagecreatetruecolor($width, $height);
            
            if (!$image) {
                throw new \Exception('Failed to create image');
            }
            
            // 设置背景色
            $bg_color = imagecolorallocate($image, 255, 255, 255);
            imagefill($image, 0, 0, $bg_color);
            
            // 生成验证码
            $code = sprintf('%04d', rand(1000, 9999));
            Session::set('captcha', $code);
            
            // 设置文字颜色
            $text_color = imagecolorallocate($image, 0, 0, 0);
            
            // 绘制验证码
            imagestring($image, 5, 35, 12, $code, $text_color);
            
            // 设置HTTP头
            header('Content-Type: image/png');
            header('Cache-Control: no-cache, no-store, must-revalidate');
            header('Pragma: no-cache');
            header('Expires: 0');
            
            // 输出图片
            imagepng($image);
            imagedestroy($image);
            
        } catch (\Exception $e) {
            // 如果出错，输出一个简单的错误图片
            header('Content-Type: image/png');
            $error_image = imagecreate(120, 40);
            $bg = imagecolorallocate($error_image, 255, 255, 255);
            $text = imagecolorallocate($error_image, 255, 0, 0);
            imagestring($error_image, 3, 30, 15, 'ERROR', $text);
            imagepng($error_image);
            imagedestroy($error_image);
        }
        
        exit;
    }
}
